//
//  DataCache.m
//  QQ13
//
//  Created by KL on 16/11/15.
//  Copyright © 2016年 KM. All rights reserved.
//

#import "DataCache.h"
#import "LoginData.h"
#import "SearchController.h"

@implementation DataCache

+ (void)loginWithName:(NSString *)name Password:(NSString *)password complete:(void (^)(NSDictionary *))handle
{
    NSDictionary *param = @{
                            @"name":name,
                            @"password":password
                            };
    
    [self getWithParam:param URLstring:@"http://xl18z.cn/login.php" complete:^(NSDictionary *data) {
        handle(data);
    }];
    
}

+ (void)getListPage:(int)page complete:(void (^)(NSDictionary *))handle
{
    NSDictionary *param = @{
                            @"page":@(page)
                            };
    [self getWithParam:param URLstring:@"http://xl18z.cn/list.php" complete:^(NSDictionary *data) {
        handle(data);
    }];
}

+ (void)getWithParam:(NSDictionary *)param URLstring:(NSString *)urlstring complete:(void (^)(NSDictionary *data))handle
{
    NSMutableString *str = [[NSMutableString alloc]initWithString:urlstring];
    [str appendString:@"?"];
    for (NSString *key in param) {
        [str appendFormat:@"%@=%@&",key,param[key]];
    }
    NSString *str2 = [str substringToIndex:str.length - 1];
    
    NSURL *url = [NSURL URLWithString:str2];
    
    NSURLRequest *re = [NSURLRequest requestWithURL:url];
    NSURLSession *s = [NSURLSession sharedSession];
    NSURLSessionDataTask *tas = [s dataTaskWithRequest:re completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
        
            handle(dic);
        });
    }];
    [tas resume];
    
}
@end
